package com.example.demo.service.impl;

import com.example.demo.entity.ShoppingCart;
import com.example.demo.mapper.ShoppingCartMapper;
import com.example.demo.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 购物车服务实现类
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public void addToCart(ShoppingCart shoppingCart) {
        shoppingCartMapper.insert(shoppingCart);
    }

    @Override
    public void removeFromCart(Integer userId, Integer productId) {
        ShoppingCart cart = shoppingCartMapper.findByUserIdAndProductId(userId, productId);
        if (cart != null) {
            shoppingCartMapper.deleteById(cart.getCartId());
        }
    }

    @Override
    public void updateQuantity(Integer userId, Integer productId, Integer quantity) {
        ShoppingCart cart = shoppingCartMapper.findByUserIdAndProductId(userId, productId);
        if (cart != null) {
            cart.setQuantity(quantity);
            shoppingCartMapper.updateById(cart);
        }
    }

    @Override
    public List<ShoppingCart> getUserCart(Integer userId) {
        return shoppingCartMapper.findByUserId(userId);
    }

    @Override
    public void clearUserCart(Integer userId) {
        List<ShoppingCart> userCart = getUserCart(userId);
        for (ShoppingCart cart : userCart) {
            shoppingCartMapper.deleteById(cart.getCartId());
        }
    }

    @Override
    public ShoppingCart getCartItem(Integer userId, Integer productId) {
        return shoppingCartMapper.findByUserIdAndProductId(userId, productId);
    }
}